
# fastlane_version "2.112.0"
default_platform :android

platform :android do

  #firim token
  FirToken = "*"
  #蒲同英
  PgyerApiKey = "*"

  # 生产包目录
  ProductionDir  = "/Users/#{`whoami`}/Desktop/ipa_appStore".gsub("\n", "")
    # 开发包目录
  DevelopmentDir  = "/Users/#{`whoami`}/Desktop/ipa_development".gsub("\n", "")
  

  ## Common
  desc "打包 development 版本, to: pgy/fir"
  private_lane :build do |options|

    versionName = getVersion()
    versionCode = versionName.gsub(".", "");

    gradle(
      task: 'assemble',
      build_type: options[:type] || 'Release',
      # project_dir: project_dir,
        properties: {
          "android.injected.version.code" => versionCode,
          "android.injected.version.name" => versionName,
        }
    )
  end

  desc "打包并上传 develop 版本, to: pgy/fir"
  lane :release do |options|
    platform = options[:to]
    platform = platform ? platform : "pgy"

    type = 'Release'
    build(type: type)
    filePath = rename(type: type);

    if platform.start_with?"fir"
      uploadFir(filePath: filePath)
    else
      uploadPgyer(filePath: filePath)
    end
  end


  desc "打包并上传 develop 版本, to: pgy/fir"
  lane :develop do |options|
    platform = options[:to]
    platform = platform ? platform : "pgy"

    type = options[:type] || 'Release'
    build(type: type)
    filePath = rename(type: type, ipaDir: DevelopmentDir);

    if platform.start_with?"fir"
      uploadFir(filePath: filePath)
    else
      uploadPgyer(filePath: filePath)
    end

  end


  desc "打包并上传 develop 版本, to: pgy/fir"
  lane :upload do |options|
    platform = options[:to]
    platform = platform ? platform : "pgy"

    fileName = getAppName()

    fileDir = DevelopmentDir
    filePath = "#{fileDir}/#{fileName}.apk"
    UI.message "upload fileName: #{fileName}"
    UI.message "upload filePath: #{filePath}"

    if platform.start_with?"fir"
      uploadFir(filePath: filePath)
    else
      uploadPgyer(filePath: filePath)
    end

  end


  desc "上传ipad 到 firim"
  def uploadFir(filePath: String, firToken: FirToken)
    response = firim(
      firim_api_token: firToken,
      icon: ENV["App_Icon_Local"],
      apk: filePath
    )
    UI.message "firim response: #{response.to_json}"
    # handleDingTalk(name: name, ipaDir: ipaDir, downloadUrl: ENV["Firim_Shortcut_Link"])
  end


  desc "上传ipad 到 Pgyer"
  def uploadPgyer(filePath: String, apiKey: PgyerApiKey)
    # uploadtime = Time.now.strftime("%Y%m%d%H%M")
    uploadtime = Time.now.strftime("%Y-%m-%d %H:%M:%S")

    response = pgyer(
      api_key: apiKey,
      # update_description: "fastlane自动打包上传测试 pgyer",
      update_description: "#{uploadtime}",
      install_type: "1",
      apk: filePath,
    )

    UI.message "pgyer response: #{response.to_json}"
    UI.message "pgyer buildQRCodeURL: #{response["buildQRCodeURL"]}".blue

    handleDingTalk(
      filePath: filePath,
      downloadUrl: response["fastlaneAddedWholeVisitUrl"],
      qrcodeURL: response["buildQRCodeURL"]
    )
  end


  desc "webhook 钉钉"
  def handleDingTalk(filePath: String, downloadUrl: String, qrcodeURL: String)
    appVersion = getVersion()

    params = {appPath: filePath,
              appName: ENV["app_name"],
              appVersion: appVersion,
              appIcon: qrcodeURL,
              dingUrl: ENV["Dingtalk_Url"],
              slogan: ENV["APP_Slogan"],
              downloadUrl: downloadUrl,
              }

    UI.message "handleDingTalk: #{params.to_json}".blue
    dingdingtalk_robot(params)
  end


  desc "rename"
  def rename(type: 'Release', ipaDir: ProductionDir)
    fileName = getAppName();
    UI.message "fileName: #{fileName}"

    current = getProjectDir();

    apkDir = "#{current}/build/app/outputs/flutter-apk"
    apkPath = "#{apkDir}/app-#{type.downcase}.apk"
    apkPathNew = "#{apkDir}/#{fileName}.apk"

    sh("mv #{apkPath} #{apkPathNew}")

    ipaPath = "#{ipaDir}/#{fileName}.apk"
    sh("mv #{apkPathNew} #{ipaPath}")
    return ipaPath;
  end


  desc "getAppName"
  def getAppName()
    # time = Time.now.strftime("%Y-%m-%d-%H-%M-%S")
    time = Time.now.strftime("%Y-%m-%d")
    fileName = "#{getSchemeName()}_v#{getVersion()}_#{time}"
    UI.message "fileName: #{fileName}"
    return fileName;
  end


  desc "getSchemeName"
  def getSchemeName()
    yamlMap = getYamlMap();
    name = yamlMap["name"]
    UI.message "schemeName: #{name}"
    return name;
  end


  desc "getVersion"
  def getVersion()
    yamlMap = getYamlMap();
    version = yamlMap["version"].split("+")[0]
    UI.message "version: #{version}"
    return version
  end


  desc "getYamlMap"
  def getYamlMap()
    current = getProjectDir();
    UI.message "current: #{current}"

    yaml_path = File.join(current, "pubspec.yaml");
    result = yaml_from_path(path: yaml_path);
    return result
  end


  desc "getProjectDir"
  def getProjectDir()
    current = Dir.pwd;
    current = File.expand_path("..", current);
    current = File.expand_path("..", current);

    UI.message "#{__method__}: #{current}"
    return current;
  end


  desc "测试"
  lane :test do

    current = getProjectDir();
    UI.message "current: #{current}"

    fileName = getAppName()

    fileDir = DevelopmentDir
    filePath = "#{fileDir}/#{fileName}.apk"
    UI.message "upload fileName: #{fileName}"
    UI.message "upload filePath: #{filePath}"

  end


  # You can define as many lanes as you want
  after_all do |lane|

  end

  error do |lane, exception|

  end
end


# More information about multiple platforms in fastlane: https://github.com/fastlane/fastlane/blob/master/fastlane/docs/Platforms.md
# All available actions: https://docs.fastlane.tools/actions

# fastlane reports which actions are used. No personal data is recorded.
# Learn more at https://github.com/fastlane/fastlane#metrics


# fastlane ios developupload to: pgy